package com.qh.user.service.impl;

import com.qh.basic.exception.BusinessException;
import com.qh.basic.util.Md5Utils;
import com.qh.basic.util.StrUtils;
import com.qh.org.domain.Employee;
import com.qh.org.domain.Shop;
import com.qh.user.domain.Logininfo;
import com.qh.user.domain.User;
import com.qh.user.mapper.LogininfoMapper;
import com.qh.user.mapper.UserMapper;
import com.qh.user.service.IUserService;
import com.qh.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(Map<String, String> map) {
        //一.校验
        //1.空值校验
        String phoneCode = map.get("phoneCode");
        String phone = map.get("phone");
        String password = map.get("password");
        String confirmPassword = map.get("confirmPassword");
        if (StringUtils.isEmpty(phoneCode) || StringUtils.isEmpty(phone) ||
                StringUtils.isEmpty(password) || StringUtils.isEmpty(confirmPassword)){
            throw new BusinessException("信息不能为空");
        }
        //2.校验两次密码是否一致
        if (!password.equals(confirmPassword)){
            throw new BusinessException("两次输入密码不一致");
        }
        //3.校验验证码是否输入正确[或者过期]
        Object objRedis = redisTemplate.opsForValue().get("register:" + phone);
        if(objRedis==null){
            throw new BusinessException("手机验证码过期");
        }
        //redis中手机验证码的存储格式【业务键:手机号码 - 验证码:时间戳】
        if(!phoneCode.equals(objRedis.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误");
        }
        //二.添加到数据库
        //将一个对象转换为另一个对象，而且字段较多的时候就用user2Loginingo
        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加logininfo
        logininfoMapper.save(logininfo);
        //2.再添加user
        user.setLogininfoId(logininfo.getId());//将返回的id设置给user的logininfoId
        userMapper.save(user);
    }

    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        //一.校验
        //1.空值校验
        String email = map.get("email");
        String password = map.get("password");
        String confirmPassword = map.get("confirmPassword");
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)){
            throw new BusinessException("信息不能为空");
        }
        //2.校验两次密码是否相同
        if (!password.equals(confirmPassword)){
            throw new BusinessException("两次输入密码不一致");
        }
        //3.校验邮箱是否被注册过
       User userTem = userMapper.loadByEmail(email);
        if (userTem != null){
            throw new BusinessException("该邮箱已经注册过，请直接登录，忘记密码请联系管理员");
        }
        //二.添加到数据库
        User user = new User();
        user.setUsername(email);
        user.setEmail(email);
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Password = Md5Utils.encrypByMd5(password+salt);
        user.setPassword(md5Password);
        user.setState(0);
        //使用beanUtils的方法，属性同名原则进行克隆。
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        //1.先添加t_logininfo
        logininfo.setDisable(false);
        logininfo.setType(1);
        logininfoMapper.save(logininfo);
        //2.再添加user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
        //三.发送邮件提醒用户激活
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("1638857628@qq.com");
        helper.setSubject("用户激活通知");
        //true - 能够再内容中编写html标签 - 复杂邮件会解析
        helper.setText("<h1>注册成功!!!</h1>'<a href='http://127.0.0.1:8080/user/active/"+user.getId()+"'>点击该链接激活使用</a>",true);
        //收件人
        helper.setTo(user.getEmail());
        javaMailSender.send(mimeMessage);

    }

    @Override
    public void updateById(Long id) {
        User user = userMapper.loadOne(id);
        user.setState(1);
        Long logininfoId = user.getLogininfoId();
        Logininfo logininfo = logininfoMapper.loadOne(logininfoId);
        logininfo.setDisable(true);
        userMapper.update(user);
        logininfoMapper.update(logininfo);
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //使用工具类，属性同名原则，克隆属性给另外一个对象
        //设置它两默认为开启
        logininfo.setType(1);
        logininfo.setDisable(true);
        BeanUtils.copyProperties(user,logininfo);
        return logininfo;
    }

    private User map2User(Map<String, String> map) {
        User user = new User();
        user.setUsername(map.get("phone"));
        user.setPhone(map.get("phone"));
        //生成随机的32位盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //加密加盐
        String md5Password = Md5Utils.encrypByMd5((map.get("password") + salt));
        user.setPassword(md5Password);
        user.setState(1);
        return user;
    }

    /**
     * 添加重构
     * @param user
     */
    @Transactional
    @Override
    public void save(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);//获取到自增ID

        //添加user的数据
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }

    /**
     * 删除方法重构
     * @param id
     */
    @Override
    public void del(Long id) {
        //先查询登陆信息id
        User user = userMapper.loadOne(id);
        //删除user
        super.del(id);
        //删除logininfo
        logininfoMapper.del(user.getLogininfoId());
    }

    /**
     * 修改方法重构
     * @param user
     */
    @Transactional
    @Override
    public void update(User user) {
        //处理盐值和密码-每次修改都刷新盐值了的
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //将原始的logininfo_id,与shop_id设置到前端传过来的user对象
        User oldUser = userMapper.loadOne(user.getLogininfoId());
        user.setLogininfoId(oldUser.getLogininfoId());
        //修改user
        super.update(user);

        //修改logininfo
        Logininfo oldLogininfo = logininfoMapper.loadOne(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }
}
